package com.gitee.feizns.quickstart.log.spring.boot.autoconfigure.db;

import com.gitee.feizns.dynamic.reflect.Constructors;
import com.gitee.feizns.quickstart.log.LogAroundAspectListener;
import com.gitee.feizns.quickstart.log.LogUserIdSupplier;
import com.gitee.feizns.quickstart.log.MethodLog;
import com.gitee.feizns.quickstart.log.QkLogErrorType;
import com.mybatisflex.core.query.QueryChain;

import java.util.function.BiFunction;

/**
 * @author feizns
 * @since 2025/1/6
 */
public class MybatisFlexSaveToDbLogListener<T extends DbLog<T>> implements LogAroundAspectListener {

    /**
     * 日志类
     */
    private final Class<T> logClass;

    /**
     * 错误类型
     */
    private final QkLogErrorType errorType;

    /**
     * mybatis flex 保存到数据库日志监听器
     * @param logClass 日志类
     */
    public MybatisFlexSaveToDbLogListener(Class<T> logClass) {
        this(logClass, QkLogErrorType.Message);
    }

    /**
     * mybatis flex 保存到数据库日志监听器
     * @param logClass  日志类
     * @param errorType 错误类型
     */
    public MybatisFlexSaveToDbLogListener(Class<T> logClass, QkLogErrorType errorType) {
        this.logClass = logClass;
        this.errorType = errorType;
    }

    @Override
    public void listener(MethodLog log) {
        T instance = Constructors.newInstance(logClass);
        instance.apply(log, errorType);
        QueryChain.of(logClass).baseMapper().insert(instance);
    }

}
